package org.fastsyncer.manager.listener;

import org.fastsyncer.common.entity.MappingTask;
import org.fastsyncer.manager.framework.DataFactory;
import org.fastsyncer.manager.framework.ManagerFactory;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public abstract class AbstractListener implements LifecycleListener {

    private static final Logger logger = LoggerFactory.getLogger(AbstractListener.class);
    
    /**
     * 驱动ID
     */
    protected String driverId;
    
    // 存储服务
    private DataFactory data = DataFactory.getInstance();
    
    // 数据迁移/同步服务
    private ManagerFactory manager = ManagerFactory.getInstance();
    
    /**
     * 设置驱动ID
     * @param id
     * @return 监听器
     */
    protected AbstractListener setDriverId(String id) {
        this.driverId = id;
        return this;
    }
    
    /**
     * 获取驱动ID
     * @return 驱动ID
     */
    public String getDriverId() {
        return driverId;
    }
    
    /**
     * 获取驱动配置
     * @return MappingTask
     */
    protected MappingTask getMapping(){
        return data.getMapping(driverId);
    };
    
    /**
     * 获取驱动增量配置
     * @param clazz 配置类型
     * @return Meta
     */
    protected <T> T getMappingMeta(Class<T> clazz){
        return data.getMappingMeta(driverId, clazz);
    };
    
    /**
     * 保存驱动增量配置
     * @param meta 配置对象<Class ? extends Meta>
     * @return true/false
     */
    protected <T> boolean saveMappingMeta(T meta){
        return data.saveMappingMeta(driverId, meta);
    };
    
    /**
     * 发送消息
     * @param msg 解析的增量数据
     * @throws Exception
     */
    protected void sendMsg(JSONArray msg) {
        try {
            // 将增量消息发送给manager处理
            if (null != msg && 0 < msg.length()) {
                JSONObject t = new JSONObject();
                t.put("taskId", driverId);
                t.put("msg", msg);
                manager.handle(t);
            }
        } catch (Exception e) {
            logger.error("Parse error, please check the driver configuration first.", e.getLocalizedMessage());
        }
    };
}
